package com.h3c.nem.client;

import com.alibaba.fastjson.JSONObject;
import com.h3c.nem.entity.SdUser;
import com.h3c.nem.mapper.SdUserMapper;
import com.h3c.nem.service.CommService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 每天更新部门，登录人信息，汇率，带宽数据
 */
@Log4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class AutoUpdateDataTask {

    @Autowired
    CommService commService;

    @Autowired
    SdUserMapper sdUserMapper;

    @Autowired
    DataCenterFeignClient dataCenterFeignClient;


    //3.添加定时任务
//    @Scheduled(cron = "0 15 7 * * ?")
    //每天8.15执行更新
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        log.debug("执行数据更新任务,start..." );
        //更新操作员和登录系统的用户的基本信息
        updateUserData();


        log.debug("执行数据更新任务,finish..." );
    }

    public void updateUserData() {
        List<String> notExistsUserList = new ArrayList<>();
        //初始化操作员数据
        List<SdUser> users = sdUserMapper.queryList(new SdUser());
        if (users != null) {
            users.forEach(userDo -> {
                Map<String, String> userMap = callEosMidDataUserApi(userDo.getUserId());
                if(userMap== null){
                    notExistsUserList.add(userDo.getUserId()+"/"+userDo.getUserName());
                }
                String mobile = userMap.get("mobile");
                String email = userMap.get("email");
                userDo.setPhoneNo(mobile);
                userDo.setEmail(email);
                sdUserMapper.updateById(userDo);
            });
        }

        if(notExistsUserList.size()>0){
            String emailTitle = "新员工系统-系统用户失效通知";
            String emailContent = "系统管理员，您好！" +
                                 "&nbsp;&nbsp;&nbsp;&nbsp;系统自动扫描发现以下系统用户的信息目前已经失效，请登录系统进行调整。<br>"+
                                 String.join("&nbsp;&nbsp;,&nbsp;&nbsp;",notExistsUserList);
            commService.noticeAdmins(emailTitle, emailContent);
        }
    }

    public Map<String, String> callEosMidDataUserApi(String userId){
        JSONObject basicInfoJson = dataCenterFeignClient.queryLoginUserInfo("{\"empCode\":\"" + userId + "\"}", commService.getEosToken());
        List<Map<String, String>> basicInfoList = (List<Map<String, String>>) basicInfoJson.get("data");
        if (CollectionUtils.isEmpty(basicInfoList)) {
           return null;
        }
        return basicInfoList.get(0);


    }



}
